package com.runen.wnhz.runen.ui.fragment.major;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.google.gson.Gson;
import com.runen.wnhz.runen.R;
import com.runen.wnhz.runen.bean.LessonRelativeInfoBean;
import com.runen.wnhz.runen.common.utils.NetUtils;
import com.runen.wnhz.runen.common.utils.OkHttpUtils;
import com.runen.wnhz.runen.common.utils.ToastUtil;
import com.runen.wnhz.runen.data.entity.CatalogListEntity;
import com.runen.wnhz.runen.data.entity.LessonIntroductionEntity;
import com.runen.wnhz.runen.data.entity.TestListEntity;
import com.runen.wnhz.runen.di.component.ApplicationComponent;
import com.runen.wnhz.runen.di.component.DaggerCourseDetailsComponent;
import com.runen.wnhz.runen.di.module.CourseDetailsModule;
import com.runen.wnhz.runen.presenter.Contart.CourseDetailsContart;
import com.runen.wnhz.runen.presenter.iPresenter.ICourseDetailsPresenter;
import com.runen.wnhz.runen.ui.adapter.puadapter.LessonCatalogAdapter;
import com.runen.wnhz.runen.ui.fragment.BaseFragment;
import com.runen.wnhz.runen.widget.TitleBuilder;

import java.io.IOException;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by Administrator on 2018-04-13.
 */

public class CatalogFragment extends BaseFragment<ICourseDetailsPresenter> implements CourseDetailsContart.View {
    @BindView(R.id.list_catalog)
    ListView listCatalog;
    Unbinder unbinder;
    private List<LessonRelativeInfoBean.DataBean.TitleListBean> titleListBeans;
    private Bundle bundle;

    /**
     * Lesson_formIntroduction需要的参数
     *
     * @param lid 必填
     * @return
     */
    public static CatalogFragment newInstance(String lid) {
        CatalogFragment fragment = new CatalogFragment();
        Bundle bundle = new Bundle();
        bundle.putString("lid", lid);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void setupAcitivtyComponent(ApplicationComponent appComponent) {
        DaggerCourseDetailsComponent.builder().applicationComponent(appComponent)
                .courseDetailsModule(new CourseDetailsModule(this))
                .build().inject(this);
    }

    @Override
    protected int getLayoutView() {
        return R.layout.catalog_fragment_layout;
    }

    @Override
    public void initUiAndListener(View view) {

    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(getUserVisibleHint()) {
            getLessonCatalogFragment(bundle);
        }
    }

    private void getLessonCatalogFragment(Bundle bundle) {
        if(bundle != null) {
            if (bundle.getString("lid") != null) {
                FormBody formBody = new FormBody.Builder().add("lid", bundle.getString("lid")).build();
                //构建一个网络请求，从指定网址上面请求数据
                Request.Builder requestBuilder = new Request.Builder()
                        .url(NetUtils.LESSON_RELATIVE_INFO)
                        .post(formBody);
                //创建Call对象
                Call newCall = OkHttpUtils.getOkHttpClient().newCall(requestBuilder.build());
                newCall.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtil.showToast("数据请求失败");
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, final Response response) throws IOException {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    handleCatelogJsonData(response);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                    ToastUtil.showToast("数据请求异常");
                                }
                            }
                        });
                    }
                });
            }
        }
    }

    private void handleCatelogJsonData(Response response) throws IOException {
        if (response.isSuccessful()) {
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                String json = responseBody.string();
                LessonRelativeInfoBean lessonRelativeInfoBean = new Gson().fromJson(json, LessonRelativeInfoBean.class);
                if (lessonRelativeInfoBean != null) {
                    if ("0".equals(lessonRelativeInfoBean.getRe())) {
                        ToastUtil.showToast(lessonRelativeInfoBean.getInfo());
                    } else if ("1".equals(lessonRelativeInfoBean.getRe())) {
                        titleListBeans = lessonRelativeInfoBean.getData().getTitleList();
                         listCatalog.setAdapter(new LessonCatalogAdapter(titleListBeans,getActivity()));
                    }
                }
            }
        }
    }

    @Override
    protected void init() {
        super.init();
        bundle = getArguments();
//        if (bundle != null) {
//            if (ACacheUtlis.getInstance().getReqeustUser(getActivity()) != null) {
//                mPresenter.getCatalog(ACacheUtlis.getInstance().getReqeustUser(getActivity()).getToken(),
//                        bundle.getString("lid"),page + "");
//            }
//            getLessonCatalogFragment(bundle);
//        }
    }

    @Override
    public void initToolBar(TitleBuilder mTitleBuilder) {
        setToolBarVisible(View.GONE);
    }

    @Override
    public void showLoadding() {

    }

    @Override
    public void dimissLoding() {

    }

    @Override
    public void showErrorMessage(String msg) {

    }


    @Override
    public void onTitleButtonClicked(TitleBuilder.TitleButton clicked) {

    }

    @Override
    public void getLessonIntroRequest(LessonIntroductionEntity data) {

    }

    @Override
    public void getLessonTestRequest(TestListEntity data) {

    }

    @Override
    public void getCatalogRequest(List<CatalogListEntity> data) {
        Log.e("===", data.get(0).toString());
//        CatalogAdapter adapter = new CatalogAdapter(getActivity(), data);
//        ryCatalog.setAdapter(adapter);
//        dismissProgressDialog();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
